﻿@model DashboardModel
@{
    var i = Model.CurrentInstance;
    if (i == null) { return; }
    var dbCache = i.Databases;
    var dbs = i.Databases.SafeData();
    var n = i as SQLNode;
    var replicationInfo = n?.AvailabilityGroups
        .SafeData(true)
        .Select(ag => ag.LocalReplica)
        .Where(r => r != null)
        .SelectMany(ag => ag.Databases)
        .ToDictionary(db => db.DatabaseName) ?? new Dictionary<string, SQLNode.AGDatabaseReplica>();
}
<script>
    $(function () {
        $(document).on('click', '.database-row', function () {
            var dbName = $(this).data('dbname');
            if (dbName) {
                window.location.hash = '#/db/' + encodeURIComponent(dbName) + '/tables';
            }
        });
        var header = $('.js-databases-table .category-row').detach();
        $('.js-databases-table').tablesorter({
            headers: {
                1: { sorter: 'cellText' },
                3: { sorter: 'cellText' },
                4: { sorter: 'dataVal', sortInitialOrder: 'desc' },
                5: { sorter: 'dataVal', sortInitialOrder: 'desc' },
                6: { sorter: 'dataVal', sortInitialOrder: 'desc' }
            }
        });
        header.prependTo('.js-databases-table thead');
    })
</script>
<div class="js-refresh" data-name="databases">
<h5 class="page-header">
    @dbs.GetWorstStatus().IconSpan() @(dbs?.Count.Pluralize("Database") ?? "No Databases") on @i.Name:
    @Poll.Now(i, dbCache)
</h5>
<partial name="PollInfo" model="@(new Opserver.Views.PollInfoModel { Cache = i.Databases, Name = i.Name + " databases" })" />
@if (dbs?.Any() ?? false)
{
    <table class="table table-striped table-hover text-nowrap table-super-condensed table-responsive js-databases-table">
        <thead>
            <tr>
                <th>Name</th>
                <th>State</th>
                <th>Recovery</th>
                <th>Log Wait</th>
                <th>Size <span class="text-muted">/ Log</span></th>
                <th>Last Backup</th>
                <th>Last Full</th>
            </tr>
        </thead>
        <tbody>
        @foreach (var db in dbs.OrderBy(b => b.IsSystemDatabase).ThenBy(b => b.Name))
        {
            var bkup = db.Backups?.FirstOrDefault();
            SQLNode.AGDatabaseReplica replica;
                <tr class="database-row @db.RowClass()" data-dbname="@db.Name" role="button">
                    <td>
                        <i class="fa fa-database @DatabasesModel.GetDatabaseClass(db)" aria-hidden="true"></i>
                        @db.Name
                        @if (db.IsReadOnly)
                        {
                            <span class="text-warning">(read-only)</span>
                        }
                    </td>
                    <td class="@db.TextClass()">
                        @db.State.AsString(EnumFormat.Description) <span class="text-muted">(@(((int)db.CompatibilityLevel).ToString()))</span>
                        @if (replicationInfo.TryGetValue(db.Name, out replica))
                        {
                            @replica.SynchronizationState.ToSpan()
                        }
                    </td>
                    <td>@db.RecoveryModel.AsString(EnumFormat.Description)</td>
                    <td class="@(db.LogReuseWait == LogReuseWaits.Nothing ? "text-muted" : null)">
                        @db.LogReuseWait.AsString(EnumFormat.Description)
                    </td>
                    @if (db.LogSizeMB.HasValue && db.LogSizeUsedMB.HasValue)
                    {
                        <td data-val="@((db.TotalSizeMB*1024*1024).ToString(CultureInfo.InvariantCulture))" title="Log Size: @((db.LogSizeMB.Value*1024*1024).ToSize())
Used: @((db.LogSizeUsedMB.Value*1024*1024).ToSize())
(@db.LogPercentUsed.GetValueOrDefault(0).ToString("#,##0.###")% full)
VLF Count: @(db.VLFCount?.ToComma() ?? "unknown")">
                            @((db.TotalSizeMB * 1024 * 1024).ToSize()) <span class="text-muted">/ @((db.LogSizeMB.Value * 1024 * 1024).ToSize())</span>
                        </td>
                    }
                    else
                    {
                        <td data-val="@((db.TotalSizeMB*1024*1024).ToString(CultureInfo.InvariantCulture))">@((db.TotalSizeMB * 1024 * 1024).ToSize())</td>
                    }
                    @if (bkup?.LastBackupSizeBytes != null)
                    {
                        <td data-val="@(bkup.LastBackupStartDate?.ToEpochTime().ToString())">@(bkup.LastBackupStartDate?.ToRelativeTimeSpan())</td>
                        <td data-val="@(bkup.LastFullBackupStartDate?.ToEpochTime().ToString())" title="Backed up to: @bkup.LastFullBackupPhysicalDeviceName">
                            @if (bkup.LastFullBackupCompressedSizeBytes.HasValue)
                            {
                                @(bkup.LastFullBackupStartDate?.ToRelativeTimeSpan())
                                <span class="text-muted">(@(((double)bkup.LastFullBackupCompressedSizeBytes.Value).ToSize()))</span>
                            }
                        </td>
                    }
                    else
                    {
                        <td class="text-warning">Not found</td>
                        <td class="text-warning">Not found</td>
                    }
                </tr>
            }
        </tbody>
        <tfoot>
        @if (dbs.Any())
        {
                <tr class="total-row">
                    <td><strong>Total</strong> <span class="text-muted">(@dbs.Count.Pluralize("database"))</span></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td>
                        @((dbs.Sum(db => db.TotalSizeMB) * 1024 * 1024).ToSize())
                        <span class="text-muted"> / @((dbs.Sum(db => db.LogSizeMB ?? 0) * 1024 * 1024).ToSize())</span>
                    </td>
                    <td></td>
                    <td></td>
                </tr>
            }
            else
            {
                <tr>
                    <td colspan="7">
                        <div class="no-content">There seem to be no databases, even master, this doesn't seem right.</div>
                    </td>
                </tr>
            }
        </tfoot>
    </table>
}
</div>